package com.ruoyi.web.controller.credit;

import java.util.*;
import java.text.SimpleDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ICreditStatisticsService;
import com.ruoyi.common.utils.DateUtils;

/**
 * 信用统计分析控制器
 * 
 * @author ruoyi
 * @date 2024-01-26
 */
@RestController
@RequestMapping("/credit/admin/stats")
public class CreditStatisticsController extends BaseController
{
    @Autowired
    private ICreditStatisticsService creditStatisticsService;

    /**
     * 获取用户行为分析数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/userBehavior")
    public AjaxResult getUserBehaviorAnalysis(@RequestParam(required = false) String[] dateRange,
                                             @RequestParam(required = false) Boolean detail)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getUserBehaviorAnalysis(startDate, endDate);
            
            // 如果需要详细数据
            if (detail != null && detail) {
                List<Map<String, Object>> details = creditStatisticsService.getUserBehaviorDetails(startDate, endDate);
                result.put("details", details);
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取用户行为分析数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务使用分析数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/serviceUsage")
    public AjaxResult getServiceUsageAnalysis(@RequestParam(required = false) String[] dateRange)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getServiceUsageAnalysis(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取服务使用分析数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取信用分趋势分析数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/creditTrend")
    public AjaxResult getCreditScoreTrend(@RequestParam(required = false) String[] dateRange)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getCreditScoreTrend(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取信用分趋势分析数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取异常数据监控
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/anomalies")
    public AjaxResult getAnomalyData(@RequestParam(required = false) String[] dateRange)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近7天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = cal.getTime();
            }
            
            List<Map<String, Object>> anomalies = creditStatisticsService.getAnomalyData(startDate, endDate);
            return AjaxResult.success(anomalies);
        } catch (Exception e) {
            return AjaxResult.error("获取异常数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取详细统计数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/detailed")
    public AjaxResult getDetailedStats(@RequestParam(required = false) String[] dateRange)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getDetailedStats(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取详细统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务使用详细数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/serviceDetails")
    public AjaxResult getServiceUsageDetails(@RequestParam(required = false) String[] dateRange)
    {
        try {
            // 解析日期范围
            Date startDate = new Date();
            Date endDate = new Date();
            
            if (dateRange != null && dateRange.length >= 2) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                startDate = sdf.parse(dateRange[0]);
                endDate = sdf.parse(dateRange[1]);
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            List<Map<String, Object>> details = creditStatisticsService.getServiceUsageDetails(startDate, endDate);
            return AjaxResult.success(details);
        } catch (Exception e) {
            return AjaxResult.error("获取服务使用详细数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取地区活跃度数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/regionActivity")
    public AjaxResult getRegionActivityData()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getRegionActivityData();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取地区活跃度数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务分布数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/serviceDistribution")
    public AjaxResult getServiceDistributionData()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getServiceDistributionData();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取服务分布数据失败：" + e.getMessage());
        }
    }

    // ======================== 仪表盘统计接口 ========================

    /**
     * 获取信用分分布数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/creditDistribution")
    public AjaxResult getCreditDistribution()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getCreditDistribution();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取信用分分布数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务使用趋势数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/usageTrend")
    public AjaxResult getServiceUsageTrend(@RequestParam(required = false) String timeRange)
    {
        try {
            // 根据时间范围设置查询参数
            Date startDate = new Date();
            Date endDate = new Date();
            
            if ("week".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = cal.getTime();
            } else if ("month".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -1);
                startDate = cal.getTime();
            } else if ("quarter".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -3);
                startDate = cal.getTime();
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getServiceUsageTrend(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取服务使用趋势数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取地区分布数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/regionDistribution")
    public AjaxResult getRegionDistribution()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getRegionDistribution();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取地区分布数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取收入统计数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/revenue")
    public AjaxResult getRevenueStats(@RequestParam(required = false) String timeRange)
    {
        try {
            // 根据时间范围设置查询参数
            Date startDate = new Date();
            Date endDate = new Date();
            
            if ("week".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = cal.getTime();
            } else if ("month".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -1);
                startDate = cal.getTime();
            } else if ("quarter".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -3);
                startDate = cal.getTime();
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getRevenueStats(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取收入统计数据失败：" + e.getMessage());
        }
    }
} 